package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.example.demo.service.storage.StorageFileNotFoundException;
import com.example.demo.service.storage.StorageService;

@Controller
public class FileUploadController {

	private final StorageService storageService;

	@Autowired
	public FileUploadController(StorageService storageService) {
		this.storageService = storageService;
	}

	/**
	 * 提供图片链接，用于网页显示等
	 * 
	 * @param filename
	 * @return 文件的链接等
	 */
	@GetMapping("/files/{filename:.+}")
	@ResponseBody
	public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

		Resource file = storageService.loadAsResource(filename);
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
				.body(file);
	}

//	@PostMapping("/upload")
//	public String handleFileUpload(@RequestParam("files") MultipartFile[] files,
//			RedirectAttributes redirectAttributes) {
//		List<String> messages = new ArrayList<String>();
//		for (MultipartFile file : files) {
//			storageService.store(file);
//			messages.add("You successfully uploaded: " + file.getOriginalFilename() + "!");
//		}
//		redirectAttributes.addFlashAttribute("messages", messages);
//		return "redirect:/";
//	}

//	/** 用于测试，部署需要注释 **/
//	@CrossOrigin
//	@PostMapping("/myupload")
//	@ResponseBody
//	public List<String> myUpload(@RequestParam("files") MultipartFile[] files, @RequestParam("name") String name,
//			@RequestParam("email") String email) {
//		List<String> messages = new ArrayList<String>();
//		messages.add(name);
//		messages.add(email);
//		
//		if (files.length>0) {
//			for (MultipartFile file : files) {
//				storageService.store(file);
//				messages.add("You successfully uploaded: " + file.getOriginalFilename() + "!");
//			}
//		}
//		return messages;
//	}

	@ExceptionHandler(StorageFileNotFoundException.class)
	public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
		return ResponseEntity.notFound().build();
	}

}
